<template>
  <div class="app-container">
    <div class="app-card">
      <!-- 搜索和工具栏 -->
      <div class="table-toolbar">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="商品名称">
            <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable size="small" />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="queryParams.categoryId" placeholder="请选择分类" clearable size="small">
              <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option :value="1" label="上架" />
              <el-option :value="0" label="下架" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
          <el-button type="danger" icon="el-icon-warning" size="small" @click="handleStockWarning">库存预警</el-button>
        </div>
      </div>
      
      <!-- 表格 -->
      <el-table v-loading="loading" :data="productList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column label="商品图片" width="100" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.image"
              :src="getImageUrl(scope.row.image)" 
              style="width: 50px; height: 50px"
              :preview-src-list="[getImageUrl(scope.row.image)]">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="price" label="价格" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :step="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="库存预警值" prop="stockWarning">
          <el-input-number v-model="form.stockWarning" :min="0" :step="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="product-uploader"
            action="/api/product/upload"
            :headers="{'X-Requested-With': 'XMLHttpRequest'}"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="(err) => $message.error('上传失败: ' + err)"
            :before-upload="beforeUpload"
            :with-credentials="true"
            accept="image/jpeg,image/png">
            <template v-if="form.image">
              <img 
                :src="getImageUrl(form.image)" 
                class="product-image" 
                @error="handleImageError"
                @load="handleImageLoad"
              />
            </template>
            <i v-else class="el-icon-plus product-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 库存预警对话框 -->
    <el-dialog title="库存预警" :visible.sync="warningVisible" width="800px" append-to-body>
      <el-table :data="warningList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="stock" label="当前库存" width="100" />
        <el-table-column prop="stockWarning" label="预警值" width="100" />
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdateStock(scope.row)">修改库存</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    
    <!-- 修改库存对话框 -->
    <el-dialog title="修改库存" :visible.sync="stockDialogVisible" width="400px" append-to-body>
      <el-form ref="stockForm" :model="stockForm" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ stockForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前库存">
          <span>{{ stockForm.stock }}</span>
        </el-form-item>
        <el-form-item label="新库存" prop="newStock">
          <el-input-number v-model="stockForm.newStock" :min="0" :step="1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="stockDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitStockForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProducts, addProduct, updateProduct, deleteProduct, changeProductStatus, listStockWarning, updateProductStock } from '@/api/product'
import { listAllCategories } from '@/api/category'

export default {
  name: 'Product',
  data() {
    return {
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: '',
        categoryId: '',
        status: ''
      },
      // 总记录数
      total: 0,
      // 商品列表
      productList: [],
      // 分类选项
      categoryOptions: [],
      // 加载状态
      loading: false,
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        name: '',
        categoryId: '',
        description: '',
        price: 0,
        stock: 0,
        stockWarning: 10,
        image: '',
        status: 1
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入商品库存', trigger: 'blur' }
        ]
      },
      // 库存预警对话框显示状态
      warningVisible: false,
      // 库存预警列表
      warningList: [],
      // 修改库存对话框显示状态
      stockDialogVisible: false,
      // 修改库存表单
      stockForm: {
        id: undefined,
        name: '',
        stock: 0,
        newStock: 0
      },
      // 图片加载状态
      imageLoaded: false
    }
  },
  created() {
    this.getList()
    this.getCategoryOptions()
  },
  watch: {
    // 监控图片URL变化，确保视图更新
    'form.image': {
      handler(val) {
        if (val) {
          console.log('图片URL已更新:', val)
          // 强制刷新图片
          this.$forceUpdate()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 获取商品列表
    getList() {
      this.loading = true
      listProducts({
        current: this.queryParams.current,
        size: this.queryParams.size,
        name: this.queryParams.name,
        categoryId: this.queryParams.categoryId,
        status: this.queryParams.status
      }).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.productList = response
          this.total = response.length
        } else {
          // 否则尝试获取list和total字段
          this.productList = response.list || response.records || []
          this.total = response.total || 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取分类选项
    getCategoryOptions() {
      listAllCategories().then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.categoryOptions = response
        } else {
          this.categoryOptions = response.data || []
        }
      })
    },
    // 搜索按钮点击事件
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.name = ''
      this.queryParams.categoryId = ''
      this.queryParams.status = ''
      this.queryParams.current = 1
      this.getList()
    },
    // 每页数量改变事件
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 添加按钮点击事件
    handleAdd() {
      this.dialogTitle = '添加商品'
      this.form = {
        id: undefined,
        name: '',
        categoryId: '',
        description: '',
        price: 0,
        stock: 0,
        stockWarning: 10,
        image: '',
        status: 1
      }
      this.dialogVisible = true
    },
    // 编辑按钮点击事件
    handleUpdate(row) {
      this.dialogTitle = '编辑商品'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该商品吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProduct(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 状态改变事件
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm(`确认${text}该商品吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeProductStatus(row.id, row.status).then(() => {
          this.$message.success(`${text}成功`)
        })
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    // 表单提交事件
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateProduct(this.form).then(() => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addProduct(this.form).then(() => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    // 库存预警按钮点击事件
    handleStockWarning() {
      listStockWarning().then(response => {
        // 直接使用返回的数组数据
        this.warningList = Array.isArray(response) ? response : []
        this.warningVisible = true
      })
    },
    // 修改库存按钮点击事件
    handleUpdateStock(row) {
      this.stockForm = {
        id: row.id,
        name: row.name,
        stock: row.stock,
        newStock: row.stock
      }
      this.stockDialogVisible = true
    },
    // 修改库存表单提交事件
    submitStockForm() {
      updateProductStock(this.stockForm.id, this.stockForm.newStock).then(() => {
        this.$message.success('修改库存成功')
        this.stockDialogVisible = false
        // 刷新库存预警列表
        listStockWarning().then(response => {
          // 直接使用返回的数组数据
          this.warningList = Array.isArray(response) ? response : []
        })
        // 刷新商品列表
        this.getList()
      })
    },
    // 上传前校验
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return (isJPG || isPNG) && isLt5M
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        // 重置图片加载状态
        this.imageLoaded = false;
        
        // 先清空图片防止缓存问题
        this.form.image = '';
        
        this.$nextTick(() => {
          // 检查返回的数据格式
          if (res.data && (res.data.url || res.data.filename)) {
            // 优先使用url字段，如果没有则使用filename
            this.form.image = res.data.url || res.data.filename;
            
            // 强制更新视图
            this.$forceUpdate();
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传响应格式错误');
          }
        });
      } else {
        this.$message.error(res.message || '上传失败');
      }
    },
    // 获取图片URL
    getImageUrl(image) {
      if (!image) {
        return '';
      }
      
      let url = '';
      
      if (image.startsWith('http')) {
        url = image;
      } else if (image.startsWith('/upload/')) {
        // 使用文件控制器提供的API
        const filename = image.replace('/upload/', '');
        url = `/api/file/image/${filename}`;
      } else {
        // 兼容旧数据，如果只是文件名
        url = `/api/file/image/${image}`;
      }
      
      // 添加随机参数防止缓存
      const timestamp = new Date().getTime();
      url = `${url}?t=${timestamp}`;
      
      return url;
    },
    // 处理图片加载错误
    handleImageError() {
      this.$message.error('图片加载失败，请检查网络连接');
    },
    // 处理图片加载成功
    handleImageLoad() {
      this.imageLoaded = true
    }
  }
}
</script>

<style lang="scss" scoped>
.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.product-uploader {
  .product-image {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  .product-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }
}

.image-loaded-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;

  i {
    font-size: 24px;
    color: #67c23a;
  }
}
</style> 